<template>
	<view v-if='userCoupon != ""' style='height: 100vh;overflow: auto;'>
		<view :style="backgroundStyle">
			<view class='tree' v-if='userCoupon.coupon.__metadata'>
				<view style='padding:10px 30% 0px 30%'>
					
					<img :src='userCoupon.coupon.__metadata.image ? userCoupon.coupon.__metadata.image : "/static/lettle-tree.png"' style='width:100%;height:auto'
						mode='widthFix' />
				</view>
				
			</view>

		</view>

		<view v-if='image' class='show-image'>
			<img :src='image' style='width:100%' mode='widthFix' />
		</view>
		<view v-else style='width:80%;height:80vh;position: fixed;top:10%'>
			<img :src='icon' style='width:100%;height:80vh' mode='widthFix' />
		</view>
		<view style='position: fixed;bottom:33.5vh;width:100%;z-index:999'>
			<view style='color:#fff;font-size:18px;text-align: center;font-weight: bold;'>
				{{userCoupon.code ? userCoupon.code.replace('甘链-','') : ''}}
			</view>
		</view>
		<view style='position: fixed;bottom:23vh;width:40%;left:30%;height:15vh'>
			<img src='https://picture.jmgc.vip/162f62ae-1e37-4f3d-a843-24cdef36c429.png' style='width:100%;height:auto' mode='widthFix' />
		</view>
		<view >
			<view style='padding:20px'>
				<u-button v-if='hadPhone == false' text='确定领取' type='success' shape='circle' open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"></u-button>
				<u-button v-else text='确定领取' type='success' shape='circle' @click='changeUserCouponUser'></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				image: '',
				userCoupon: '',
				solarMessage: '',
				backgroundStyle: 'width: 100%;height: 80vh;background-size: cover;background-position: center;background-repeat: no-repeat;',
				icon: '',
				userId: 0,
				hadPhone: false,
				optionData: ''
			}
		},
		onLoad(options) {
			if(typeof(options.scene) != 'undefined'){
				let optionData = options.scene.split('-')
				console.log(optionData)
				if(optionData.length != 2){
					uni.showModal({
						title: '',
						content: '参数错误，请重试！',
						showCancel: false,
						success: () => {
							uni.switchTab({
								url: '/pages/index/index'
							})
						}
					})
					return
				}
				this.optionData = optionData
				const token = uni.getStorageSync('api_token')
				if(token == ''){
					let _this = this
					uni.login({
						success(result) {
							let data = {
								code: result.code,
							}
							if(typeof(optionData[1]) != 'undefined'){
								data.recommendedUser = optionData[1]
							}else{
								data.recommendedUser = 2
							}
							_this.request.get(`wechat/mini/login`, data).then((res) => {
								uni.setStorageSync('api_token', res.data.token)
								_this.getData()
							})
						}
					})
				}else{
					this.getData()
				}
			} else {
				uni.showModal({
					title: '',
					content: '参数错误，请重试！',
					showCancel: false,
					success: () => {
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				})
			}
		},
		onShow() {

		},
		methods: {
			getData(){
				uni.showLoading()
				// 要先获取当前user信息
				this.request.get(`api/user`,{
					'@expands': `['entity.profile']`
				}).then((res) => {
					this.userId = res.data.id
					if(res.data.profile.__metadata.phone && res.data.profile.__metadata.phone != null && res.data.profile.__metadata.phone != ''){
						this.hadPhone = true
					}
					this.request.get(`api/user-coupons/find-by-share-code/${this.optionData[0]}`,
					{
						'@expands': `['entity.coupon']`
					},
					).then((res) => {
						if (res.data) {
							// 还要判断赠送人是否是当前所有者，不是的，就不能赠送
							if(res.data.user.id != this.optionData[1]){
								uni.hideLoading()
								uni.showModal({
									title: '',
									content: '已经被其他人领取了！',
									showCancel: false,
									success: () => {
										uni.switchTab({
											url: '/pages/index/index'
										})
									}
								})
								return
							}
							this.userCoupon = res.data
							// 获取特定产品的extraData，用来获取背景图，树图以及2个按钮的内容
							this.request.get(`public/products`, {
								'@filter': `entity.getCategory().getType().getSlug() == 'tree'`
							}).then((res) => {
								this.product = res.data[0]
								// 加载背景图
								this.backgroundStyle +=
									`background-image: url("${this.product.extraData.backgroundImage ? this.product.extraData.backgroundImage : ''}")`
									this.icon = this.product.extraData.icon ? this.product.extraData.icon : ''
								this.solarMessage = this.product.extraData.solarMessage ? this.product
									.extraData.solarMessage : ''
									uni.hideLoading()
							})
						} else {
							uni.hideLoading()
							uni.showModal({
								title: '',
								content: '参数错误，请重试！',
								showCancel: false,
								success: () => {
									uni.switchTab({
										url: '/pages/index/index'
									})
								}
							})
						}
					})
				})
				
			},
			// 接受
			changeUserCouponUser(){
				if(this.userId == 0){
					uni.hideLoading()
					uni.showModal({
						title: '',
						content: '用户信息错误',
						showCancel: false,
						success: () => {
							uni.switchTab({
								url: '/pages/index/index'
							})
						}
					})
				}else{
					this.request.post(`api/user-coupons/fetch/${this.optionData[0]}`).then((res) => {
						uni.showModal({
							title: '',
							content: '领取成功！',
							showCancel: false,
							success: () => {
								uni.redirectTo({
									url: `/pages/cart/tree?id=${this.userCoupon.id}`
								})
							}
						})
					} )
				}
			},
			getPhoneNumber(e) {
				let _this = this
				if (typeof(e.detail.iv) == 'undefined') {
					uni.showToast({
						title: '获取失败,请手动输入',
						icon: 'none'
					})
					return
				} else {
					uni.showLoading()
					uni.login({
						provider: "weixin",
						success: function(res) {
							let data = {
								code: res.code
							}
							_this.request.get("wechat/mini/login", data).then((res) => {
								if (res.data.data.session_key) {
									let data = {
										sessionKey: res.data.data.session_key,
										iv: e.detail.iv,
										encryptedData: e.detail.encryptedData,
									}
									_this.request.post(`wechat/decrypt-data`, data).then((res) => {
										//更新手机号码
										_this.request.put(`api/user-profile`, {
											phone: res.data.phoneNumber
										}).then((res) => {
											// 获取转赠
											_this.changeUserCouponUser()
										})
									})
								} else {
									uni.hideLoading()
									uni.showToast({
										title: '获取手机号码失败！',
										icon: 'none'
									})
								}
							})
						},
					});
				}
			},
		}
	}
</script>

<style>
	.tree {
		position: fixed;
		bottom: 38vh;
		width: 60%;
		left: 20%;
		z-index: 998;
	}

	.show-image {
		position: fixed;
		bottom: 40vh;
		z-index: 999;
		width: 60%;
		/* left: -12%; */
	}

	.solar-button {
		background-color: bisque;
		color: #909399;
		border-radius: 10px;
		padding: 3px 10px;
		margin-top: 10rpx;
	}
</style>